package com.liunian.algorithmstudy.backtracking.subsets;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class FindSubsequences491 {

	private List<List<Integer>> res = new ArrayList<>();
	private LinkedList<Integer> path = new LinkedList<>();

	public List<List<Integer>> findSubsequences1(int[] nums) {
		boolean[] used = new boolean[nums.length];
		backTracking(nums, 0, used, Integer.MIN_VALUE);
		return res;
	}

	private void backTracking(int[] nums, int index, boolean[] used, int minValue) {
		if (index == nums.length) {
			return;
		}
		Set<Integer> set = new HashSet<>();
		for (int i = index; i < nums.length; i++) {
			if (nums[i] < minValue) {
				continue;
			}
			if (i > index && nums[i] == nums[i - 1] && !used[i - 1] || set.contains(nums[i])) {
				continue;
			}
			path.add(nums[i]);
			if (path.size() > 1) {
				res.add(new ArrayList<>(path));
			}
			set.add(nums[i]);
			used[i] = true;
			backTracking(nums, i + 1, used, nums[i]);
			used[i] = false;
			path.removeLast();
		}
	}

	public static void main(String[] args) {
		FindSubsequences491 find = new FindSubsequences491();
		System.out.println(find.findSubsequences(new int[]{1,3,2,2}));
	}


	public List<List<Integer>> findSubsequences(int[] nums) {
		backTracking(nums, 0);
		return res;
	}

	private void backTracking(int[] nums, int index) {
		if (path.size() > 1) {
			res.add(new ArrayList<>(path));
		}
		Set<Integer> set = new HashSet<>();
		for (int i = index; i < nums.length; i++) {
			if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || set.contains(nums[i])) {
				continue;
			}
			path.add(nums[i]);
			set.add(nums[i]);
			backTracking(nums, i + 1);
			path.removeLast();
		}

	}

}
